App = {
    web3Provider: null,
    contracts: {},
    item_i:-1,
    item_d:-1,
    init: async function() {
        return await App.initWeb3();
    },

    initWeb3: async function() {
        // Modern dapp browsers...
        if (window.ethereum) {
            App.web3Provider = window.ethereum;
            try {
                // Request account access
                await window.ethereum.enable();
            } catch (error) {
                // User denied account access...
                console.error("User denied account access")
            }
        }
        // Legacy dapp browsers...
        else if (window.web3) {
            App.web3Provider = window.web3.currentProvider;
        }
        // If no injected web3 instance is detected, fall back to Ganache
        else {
            App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
        }
        web3 = new Web3(App.web3Provider);

        return App.initContract();
    },

    initContract: function() {
        // 加载Auction.json，保存了Adoption的ABI（接口说明）信息及部署后的网络(地址)信息，它在编译合约的时候生成ABI，在部署的时候追加网络信息
        $.getJSON('Auction.json', function(data) {
            console.log(data);
            // 用Auction.json数据创建一个可交互的TruffleContract合约实例。
            App.contracts.Auction = TruffleContract(data);
            // Set the provider for our contract
            App.contracts.Auction.setProvider(App.web3Provider);

            return App.markNFT();
        });

        setInterval(App.EndFunction,10000);
        return App.bindEvents();
    },

    TestStartAuctionFunction:function (event){
        event.preventDefault();

        // 获取用户账号
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];
            //document.getElementById("test").innerHTML=account;
            let AuctionInstance;

            App.contracts.Auction.deployed().then(function(instance) {
                AuctionInstance = instance;
                return AuctionInstance.newAuction(6000,0,{from: account});
            }).then(function(result) {
                console.log(result);
            }).catch(function(err) {
                console.log(err.message);
            });
        });
    },

    StartFirstAuctionFunction:function (event){
        event.preventDefault();
        App.item_i = parseInt($(event.target).data('id'));
    },

    StartAuctionFunction:function (){
        console.log(App.item_i);
        let price = document.getElementById("auction-price");
        let time = document.getElementById("ending-date");
        let timeStamp = new Date(time.value).getTime();
        let timeNow = Date.parse(new Date());
        App.TimerAuctionFunction.call();
        //setTimeout(App.EndFunction,timeStamp-timeNow+10000);
        // 获取用户账号
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];
            document.getElementById("test").innerHTML=account;
            let AuctionInstance;

            App.contracts.Auction.deployed().then(function(instance) {
                AuctionInstance = instance;
                return AuctionInstance.newAuction((timeStamp-timeNow)/1000, App.item_i, price.value*10000, {from: account});
            }).then(function(result) {

                console.log(result);
            }).catch(function(err) {
                console.log(err.message);
            });
        });
    },

    TimerAuctionFunction:function (){

    },

    BidFirstFunction:function (){
        event.preventDefault();
        App.item_d = parseInt($(event.target).data('id'));
    },
    BidFunction:function (){
        console.log(App.item_d);
        let price = document.getElementById("bid-price");
        // 获取用户账号
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];
            document.getElementById("test").innerHTML=account;
            console.log(account);
            let AuctionInstance;

            App.contracts.Auction.deployed().then(function(instance) {
                AuctionInstance = instance;
                return AuctionInstance.bid(App.item_d,{from: account,value: price.value*1000000000000000000});
            }).catch(function(err) {
                console.log(err.message);
            });
        });
    },


    EndFunction:function (){
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];
            console.log(account);
            // 获取用户账号
            let total_Auct;
            let AuctionInstance;
            App.contracts.Auction.deployed().then(function(instance) {
                AuctionInstance = instance;
                return AuctionInstance.totalAuction.call();
            }).then(function (data){
                console.log(data);
                total_Auct = data.c[0];
                return total_Auct;
            }).then(function (num){
                console.log(num);
                for (let i = 0; i < num; i++) {
                    //AuctionInstance.history_owners.call(1,0).then(function (data){
                    //    console.log(data);
                    //})
                    AuctionInstance.allAuctions.call(i).then(function (data){
                        let now=new Date().getTime();
                        //console.log(now/1000 >= data[2].c[0]);
                        if (now/1000 >= data[2].c[0] && data[5] === false) {
                            console.log(data);
                            AuctionInstance.AuctionEnd(i,{from:account}).catch(function(err) {
                                console.log(err.message);
                            });
                        }
                    }).catch(function(err) {
                        console.log(err.message);
                    });
                }
            }).catch(function(err) {
                console.log(err.message);
            });
        });
    },


    CreateFunction:function (){

        let name = document.getElementById("name-nft");
        let uri = document.getElementById("uri-nft");

        if(name.value === " " || uri.value===""){
            alert("用户名或密码不能为空！");
            return false;
        }

        // 获取用户账号
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];

            App.contracts.Auction.deployed().then(function(instance) {
                console.log("OK");
                AuctionInstance = instance;
                return AuctionInstance.createNFT(uri.value,name.value,{from: account});
            }).catch(function(err) {
                console.log(err.message);
            });
        });
    },

    TestFunction:function (){
        let AuctionInstance;
        document.getElementById("test").innerHTML="AAASDSDSDS"
        //setTimeout(function (){alert("Hello2")},3000);
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];
            console.log(accounts);
        });

    },

    OwnerFunction:function (event){
        event.preventDefault();
        let ID = parseInt($(event.target).data('id'));
        console.log(ID);
        let AuctionInstance;
        App.contracts.Auction.deployed().then(function(instance) {
            AuctionInstance = instance;
            return AuctionInstance.allNFTs.call(ID);
        }).then(function (data){
            console.log(data);
            let total = data[1].c[0];
            console.log("有"+total);
            let res = "Start\n";
            document.getElementById("owners").innerHTML="";
            for (let i = 0; i < total;i++){
                AuctionInstance.history_owners.call(ID,i).then(function (data){
                    document.getElementById("owners").innerHTML+="第"+(i+1)+"个拥有者:"+data+"\n";
                });
            }

        }).catch(function(err) {
            console.log(err.message);
        });
    },

    ClaimMoneyFunction:function (){
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];
            console.log(accounts);
            let AuctionInstance;
            App.contracts.Auction.deployed().then(function(instance) {
                AuctionInstance = instance;
                return AuctionInstance.withdraw({from:account});
            }).catch(function(err) {
                console.log(err.message);
            });
        });
    },

    ClaimNFTFunction:function (){
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];
            let AuctionInstance;
            let total_Auct;
            App.contracts.Auction.deployed().then(function(instance) {
                AuctionInstance = instance;
                return AuctionInstance.totalAuction.call();
            }).then(function (data){
                console.log(data);
                total_Auct = data.c[0];
                return total_Auct;
            }).then(function (num){
                console.log(num);
                for (let i = 0; i < num; i++) {
                    AuctionInstance.allAuctions.call(i).then(function (data){
                        if (data[5] === true) {
                            console.log(data);
                            let Item_index = data[1].c[0];
                            AuctionInstance.allNFTs.call(Item_index).then(function (data) {
                                if (data[4] === true){
                                    return AuctionInstance.ClaimNFT(i,{from:account});
                                }
                            });
                        }
                    }).catch(function(err) {
                        console.log(err.message);
                    });
                }
            }).catch(function(err) {
                console.log(err.message);
            });
        });
    },
    bindEvents: function() {
        $(document).on('click', '.btn-claim-money', App.ClaimMoneyFunction);
        $(document).on('click', '.btn-claim-nft', App.ClaimNFTFunction);
        $(document).on('click', '.btn-auction', App.TestStartAuctionFunction);
        $(document).on('click', '.btn-owners', App.OwnerFunction);
        $(document).on('click', '.btn-create-auction', App.StartFirstAuctionFunction);
        $(document).on('click', '.btn-go-auction', App.StartAuctionFunction);
        $(document).on('click', '.btn-go-auction', App.TimerAuctionFunction);
        $(document).on('click', '.btn-bid-auction', App.BidFirstFunction);
        $(document).on('click', '.btn-go-bid', App.BidFunction);
        $(document).on('click', '.btn-end', App.EndFunction);
        $(document).on('click', '.btn-release', App.CreateFunction);
        $(document).on('click', '.btn-test', App.TestFunction);
    },

    markNFT: function() {
        let AuctionInstance;
        // 获取用户账号
        web3.eth.getAccounts(function(error, accounts) {
            if (error) {
                console.log(error);
            }
            let account = accounts[0];

            let total_NFT;
            App.contracts.Auction.deployed().then(function(instance) {
                AuctionInstance = instance;
                return AuctionInstance.totalNFT.call();
            }).then(function (data){
                console.log(data);
                total_NFT = data.c[0];
                return total_NFT;
            }).then(function (num){
                let NFTsRow = $('#NFTsRow');
                let NFT_Template = $('#NFT-template');
                let BIDsRow = $('#BIDRow');
                let BID_Template = $('#BID-template');
                console.log(num);
                for (let i = 0; i < num; i++) {
                    AuctionInstance.allNFTs.call(i).then(function (data){
                        console.log(data);
                        let temp = false;
                        if (window.location.pathname === "/MyNFT.html" && data[1].c[0] === 1){
                            temp = true;
                        }
                        if (window.location.pathname === "/BoughtNFT.html" && data[1].c[0] !== 1){
                            temp = true;
                        }
                        //自己创建并且不在拍卖的
                        if (data[0] === account && data[4] === false && temp) {
                            NFT_Template.find('.panel-title').text(data[3]);
                            NFT_Template.find('img').attr('src', data[2]);
                            //NFT_Template.find('.pet-breed').text("");
                            NFT_Template.find('.card-price').text(20);
                            NFT_Template.find('.card-text').text("这是一张牌");
                            NFT_Template.find('.btn-create-auction').attr('data-id', i);
                            NFT_Template.find('.btn-owners').attr('data-id', i);
                            NFTsRow.append(NFT_Template.html());
                        }
                        //自己购买并且不在拍卖的

                    }).catch(function(err) {
                        console.log(err.message);
                    });
                }
            }).catch(function(err) {
                console.log(err.message);
            });

        let total_Auct;
        App.contracts.Auction.deployed().then(function(instance) {
            AuctionInstance = instance;
            return AuctionInstance.totalAuction.call();
        }).then(function (data){
            console.log(data);
            total_Auct = data.c[0];
            return total_Auct;
        }).then(function (num){
            let BIDsRow = $('#BIDRow');
            let BID_Template = $('#BID-template');
            console.log(num);
            for (let i = 0; i < num; i++) {
                //AuctionInstance.history_owners.call(1,0).then(function (data){
                //    console.log(data);
                //})
                AuctionInstance.allAuctions.call(i).then(function (data){
                    if (data[5] === false) {
                        console.log(data);
                        let benefit = data[0];
                        let highestPrice = data[4].c[0];
                        let endingTime = data[2].c[0];
                        let Item_index = data[1].c[0];
                        let res = [benefit, highestPrice, endingTime];

                        AuctionInstance.allNFTs.call(Item_index).then(function (data) {
                            let temp = false;
                            if (data[0] === account && window.location.pathname ==="/AuctionNFT.html"){
                                temp = true;
                            }
                            if (window.location.pathname ==="/Auction.html"){
                                temp = true;
                            }
                            if (temp) {
                                BID_Template.find('.panel-title').text(data[3]);
                                BID_Template.find('img').attr('src', data[2]);
                                //NFT_Template.find('.pet-breed').text("");
                                BID_Template.find('.bid-price').text(highestPrice / 10000);
                                let date = new Date(endingTime * 1000)
                                BID_Template.find('.bid-time').text(date);
                                BID_Template.find('.btn-bid-auction').attr('data-id', i);
                                BIDsRow.append(BID_Template.html());
                            }
                        });
                    }
                }).catch(function(err) {
                    console.log(err.message);
                });
            }
        }).catch(function(err) {
            console.log(err.message);
        });
        });
    }


};

$(function() {
    $(window).load(function() {
        App.init();
    });
});
